package com.baosight.risk.service.riim.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baosight.risk.api.riim.RiimRiskImportExService;
import com.baosight.risk.base.mapper.BaseMapper;
import com.baosight.risk.base.service.BaseServiceImpl;
import com.baosight.risk.common.bean.BeanUtils;
import com.baosight.risk.mapper.riim.RiimRiskImportMapper;
import com.baosight.risk.mapper.xtzy.XtzyCompanyMapper;
import com.baosight.risk.service.riim.entity.RiimRiskImport;
import com.baosight.risk.service.xtzy.entity.XtzyCompany;

import lombok.extern.slf4j.Slf4j;

@Service("riimRiskImportExServiceImpl")
@Slf4j
public class RiimRiskImportExServiceImpl extends BaseServiceImpl<RiimRiskImport> implements RiimRiskImportExService{
    @Autowired
    private RiimRiskImportMapper riskImportMapper;
    @Autowired
    private XtzyCompanyMapper companyMapper;
    
    @Override
    public BaseMapper getMapper() {
        return riskImportMapper;
    }

	@Override
	public void copyToSub(RiimRiskImport riskImport) throws Exception{
		//根据责任部门（T_RIIM_RISK_IMPORT.dept_code）去组织机构表（T_XTZY_COMPANY）获取路径（path_code）
		String deptCode = riskImport.getDeptCode();
		XtzyCompany param = new XtzyCompany();
		param.setCompCode(deptCode);
		XtzyCompany company = companyMapper.selectOne(param);
		String pathCode = company.getPathCode();
		//根据管理单位（T_RIIM_RISK_IMPORT.manage_comp_code）去组织机构表（T_XTZY_COMPANY）获取层级（path_level）
		String manageCompCode = riskImport.getManageCompCode();
		XtzyCompany param1 = new XtzyCompany();
		param1.setCompCode(manageCompCode);
		XtzyCompany mCompany = companyMapper.selectOne(param1);
		short pathLevel = mCompany.getPathLevel();
		
		//根据责任部门的路径、管理单位的层级+1查询当前管理单位的下级管理单位
		List<XtzyCompany> subManageComps = companyMapper.selectSubManageComps(pathCode, manageCompCode, pathLevel+1);
		if(subManageComps.size()>1){
			throw new Exception("不能有多个下级管理单位");
		}else if(subManageComps.size()==1){
			XtzyCompany subManageComp = subManageComps.get(0);
			//复制到子公司
			riskImport.setManageCompCode(subManageComp.getCompCode());
			riskImport.setManageCompName(subManageComp.getCompName());
			riskImport.setParentId(riskImport.getId());
			riskImport = (RiimRiskImport) BeanUtils.initBean(riskImport);
			riskImportMapper.insert(riskImport);
		}
	}

}
